package yz.cp.back.websocket.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.websocket.service.ITokenService;

import java.security.Principal;
import java.util.Map;

/**
 * Created by xukangkang on 2019/3/18.
 */
@Slf4j
public class AuthHandshakeInterceptor implements HandshakeInterceptor {
    @Autowired
    private ITokenService tokenService;
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        log.warn("handleshake before <<<<");
        String accessToken=getAccessToken(serverHttpRequest);
        if(StringUtils.isBlank(accessToken)){
            throw new RuntimeException("websocket未登录");
        }
        SecUser secUser = tokenService.retrieveUser(accessToken);
        if(secUser!=null){
            log.warn("userId:{}",secUser.getId());
            map.put("user",new MyPrincipal(secUser.getId()));
        }else {
            throw new RuntimeException("websocket未登录");
        }
        return true;
    }
    public static class MyPrincipal implements Principal {
        private String name;
        public MyPrincipal(String name){
            this.name=name;
        }
        @Override
        public String getName() {
            return name;
        }
    }
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, @Nullable Exception e) {

    }

    private String  getAccessToken(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            return serverRequest.getServletRequest().getParameter("token");
        }
        return null;
    }
}
